package 阻塞队列案例;

class MyBlockingQueue {
    private int array[] = new int[10];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    //存放
    void put(int key) throws InterruptedException {
        synchronized(this) {
            if(size >= array.length){
                //阻塞等待
                this.wait();
            }
            array[tail] = key;
            tail++;
            if(tail >= array.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    int take() throws InterruptedException {
        synchronized (this) {
            if (size == 0) {
                this.wait();
            }
            int ret = array[head];
            head++;
            if (head >= array.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class Test3 {
    public static void main(String[] args){
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        //实例创建连两个线程，一个取，一个存
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 1; i <= 10; i++){
                    try {
                        myBlockingQueue.put(i);
                        System.out.println("存放了元素" + i);
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 1; i <= 20; i++){
                    try {
                        int ret = myBlockingQueue.take();
                        System.out.println("拿到元素" + ret);
                        //Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2.start();
    }
}
